package com.chow.test;

import java.io.*;
import java.net.*;

public class RequestEngine {
	public URLConnection getURLConnection(URL connectionUrl, Parameter[] params)
			throws Exception {
		URLConnection urlConnection;
		urlConnection = connectionUrl.openConnection();
		postData(urlConnection, params);
		return urlConnection;
	}

	public void postData(URLConnection urlConnection, Parameter[] params)
			throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		if (params != null) {
			for (int i = 0; i < params.length; i++) {
				if (i != 0)
					baos.write((byte) '&');
				String name = params[i].getName();
				String value = params[i].getValue();
				String encName = URLEncoder.encode(name, "UTF-8");
				String encValue = URLEncoder.encode(value, "UTF-8");
				baos.write(encName.getBytes("UTF-8"));
				baos.write((byte) '=');
				baos.write(encValue.getBytes("UTF-8"));
			}
			urlConnection.setDoOutput(true);
			
			urlConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			OutputStream os = urlConnection.getOutputStream();
			os.write(baos.toByteArray());
			os.flush();
		} else {
			throw new Exception("No post data!");
		}
	}
}
